package authoritah.ui.eventtype;

import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import authoritah.db.EventType;


public class EventTypeController {
	private EventTypeView view;
	private EventTypeModel model;
	
	public EventTypeController() {
		ArrayList<EventType> eventTypes = EventType.getAllEventTypes();
		model = new EventTypeModel(eventTypes);
		view = new EventTypeView(model);
		
		createActions();
		view.setIcons();
	}
	
	public JPanel getDisplayComponent() {
		return view;
	}
	
	private void createActions() {
		Action addAction = new AbstractAction()
		{
			public void actionPerformed(ActionEvent arg0) {
				// Create a popup window with one field for member's name.
				String name = (String)JOptionPane.showInputDialog(
	                    view, "Event Type Name:\n", "Add Event Type", 
	                    JOptionPane.PLAIN_MESSAGE, null, null, "");
				
				// Add the new member to the datbase
				EventType newEventType = new EventType();
				newEventType.setName(name);
				EventType.createEventType(newEventType);
				
				// Finally refresh the screen.
				model.updateData(EventType.getAllEventTypes());
			}	
		};
		view.setAddAction(addAction);
		
		Action editAction = new AbstractAction()
		{
			public void actionPerformed(ActionEvent arg0) {
				EventType editEventType = view.getSelectedEventType();
				// Create a popup window with one field containing member's name
				String name = (String)JOptionPane.showInputDialog(
	                    view, "Event Type Name:\n", "Edit Event Type", 
	                    JOptionPane.PLAIN_MESSAGE, null, null, editEventType.getName());
				
				editEventType.setName(name);
				EventType.updateEventType(editEventType);
				
				// Finally refresh the screen.
				model.updateData(EventType.getAllEventTypes());
			}	
		};
		view.setEditAction(editAction);
		
		Action removeAction = new AbstractAction()
		{
			public void actionPerformed(ActionEvent arg0) {
				EventType removeEventType = view.getSelectedEventType();
				// Confirm removal of selected member
				int yesNo = JOptionPane.showConfirmDialog(view, 
						"Are you sure you wish to remove "+removeEventType.getName()+"?",
	                    "Remove Member", JOptionPane.YES_NO_OPTION);
				if (yesNo == JOptionPane.YES_OPTION)
				{
					EventType.removeEventType(removeEventType);
					
					// Finally refresh the screen.
					model.updateData(EventType.getAllEventTypes());
				}
			}	
		};
		view.setRemoveAction(removeAction);
	}
}
